package net.adetech.cjg.innerservice.utils;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

public class OcrUtil {



    public static String readChar(String base64)
    {
        ITesseract iTesseract = new Tesseract();
        String result = null;
        try {
            result = iTesseract.doOCR(getImageFormBase64(base64));
        } catch (TesseractException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String readCharByPath(String path)
    {
        ITesseract iTesseract = new Tesseract();
        String result = null;
        try {
            iTesseract.doOCR(new File(path));
        } catch (TesseractException e) {
            e.printStackTrace();
        }

        return result;
    }


    public static BufferedImage getImageFormBase64(String base64)
    {
        BufferedImage bi = null;
        try {

            byte[] bytes = new BASE64Decoder().decodeBuffer(base64);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            bi = ImageIO.read(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi;
    }


}
